package com.fengmi.service.impl;

import com.fengmi.dto.PageDTO;
import com.fengmi.entity.MallGoodsSpec;
import com.fengmi.entity.MallGoodsSpecOptions;
import com.fengmi.mapper.MallGoodsSpcMapper;
import com.fengmi.service.GoodsSpecOptionService;
import com.fengmi.vo.PageResoultVo;
import com.fengmi.vo.ResoultVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class GoodsSpecServiceImpl implements GoodsSpecOptionService {
    @Autowired(required = false)
    private MallGoodsSpcMapper mallGoodsSpcMapper;
    @Override
    public PageResoultVo<MallGoodsSpecOptions> selectSpecOptionsByPage(PageDTO<MallGoodsSpecOptions> optionsPageDTO) {
        //判断传入的前端数据是否为空
        if (optionsPageDTO==null){
            return  new PageResoultVo<>("参数非法",false);
        }
        //类型转换
        Integer page = Integer.parseInt(optionsPageDTO.getPageNum());
        Integer size = Integer.parseInt(optionsPageDTO.getPageSize());
        //非空判断,分页默认值
        if (page==null||page<=0){
            page=1;
        }
        if (size==null||size<=0){
            size=6;
        }
        //分页拦截器实现分页
        PageHelper.startPage(page,size);
        //查找所有信息
        List<MallGoodsSpecOptions> specOptsByPage = mallGoodsSpcMapper.findSpecOptsByPage(optionsPageDTO.getWhere());
        //分页信息对象创建，放入查询集合
        PageInfo<MallGoodsSpecOptions> mallGoodsSpecOptionsPageInfoPageInfo = new PageInfo<>(specOptsByPage);
        //返回分页信息
        PageResoultVo<MallGoodsSpecOptions> mallGoodsSpecOptionsPage = new PageResoultVo<>("查询成功",true);
        //设置分页信息
        mallGoodsSpecOptionsPage.setData(mallGoodsSpecOptionsPageInfoPageInfo.getList());
        //设置总页数
        mallGoodsSpecOptionsPage.setTotalPage(mallGoodsSpecOptionsPageInfoPageInfo.getPages());
        //设置总记录数
        mallGoodsSpecOptionsPage.setTotalSize(mallGoodsSpecOptionsPageInfoPageInfo.getTotal());
        return mallGoodsSpecOptionsPage;
    }

    @Override
    public ResoultVo save(MallGoodsSpec spec) {
//        判断规格
        if(spec==null){
          return  new ResoultVo(false,"非法参数");
        }
//   判断规格选项
    if (spec.getOptions()==null ||spec.getOptions().size()<=0)  {
        return  new ResoultVo(false,"非法参数");
    }
//    保存规格信息
        mallGoodsSpcMapper.addSpecOption(spec);
//    保存规格选项
        spec.getOptions().forEach(options -> {
            options.setId(spec.getId());
        mallGoodsSpcMapper.addSpecOptions(options);
        });
        return new ResoultVo(true,"添加成功");
    }
}
